import { useEffect, useState } from 'react'
import { useParams } from 'react-router-dom'
import axios from 'axios'
import { ListItem, MessItem } from '../home'
import { Image, NavBar, List, TextArea, Button, Toast } from 'antd-mobile'
import { useNavigate } from 'react-router-dom'
import withLogin from '../../components/withLogin'
import { useSelector } from 'react-redux'
const Detail = () => {
	const user = useSelector((state: any) => state.user )
	const params = useParams()
	const navigate = useNavigate()
	const [item, setItem] = useState<ListItem | null>(null)
	const [mess, setMess] = useState<MessItem>({
		name: '游客',
		id: new Date().getTime().toString(),
		content: '',
		createTime: ''
	})
	const getDetail = async (id: string) => {
		const resp = await axios.post('/api/detail', { id })
		setItem(resp.data.data)
	}
	const handleSubmit = async () => {
		if(!localStorage.getItem('token')) {
			navigate({ pathname: '/login' })
			return 
		}
		
		const resp = await axios.post('/api/mess', { id: params.id, mess: { ...mess, createTime: new Date().toLocaleDateString(), name: user || '游客' } })
		const { code, mess: message } = resp.data
		if (code === 200) {
			Toast.show({
				content: message,
			})
			params.id && getDetail(params.id)
		}
	}
	useEffect(() => {
		if (params.id) getDetail(params.id)
	}, [])
	return (
		<>
			<NavBar onBack={() => navigate(-1)}>详情页</NavBar>
			{
				item && <>
					<Image src={item.url} width={'100vw'}></Image>
					<h1>{item.desc}</h1>
					<p>{item.desc}</p>

					{/* 评论列表 */}
					<List>
						{
							item.mess.map((v, i) => {
								return <List.Item key={i}
									description={v.content}
								>
									{v.name}---{v.createTime}
								</List.Item>
							})
						}
					</List>

					{/* 提交评论 */}
					<TextArea
						showCount
						maxLength={50}
						value={mess.content}
						onChange={(value) => setMess({ ...mess, content: value })}
					></TextArea>
					<Button color="primary" onClick={() => handleSubmit()}>提交</Button>
				</>
			}
		</>
	)
}
export default withLogin(Detail)